from django.http import HttpResponse
from django.core.serializers import serialize
from django.core.cache import cache

from ...models.chat_roles import ChatRoles
from ...models.users import Users
from ...utils.users import get_login_user_id
from ...utils.time_conversion import iso_to_times

import json
import ast


def roles_list(request):
    '''
    获取角色
    '''
    userid = get_login_user_id(request, isadmin=False)
    # print(userid)

    if not userid:
        # 加载所有开放的角色
        all_chatroles = ChatRoles.objects.filter(enable=True)
    else:
        # 先从redis缓存中获取角色
        user_mes_json = cache.get(f'user_info_{userid}')

        if user_mes_json:
            user_roles_json = user_mes_json['chat_roles']
        else:
            re_user_obj = Users.objects.get(id=userid)
            # ['gpt', 'lu_xun']
            user_roles_json = ast.literal_eval(re_user_obj.chat_roles_json)

        all_chatroles = ChatRoles.objects.filter(key__in=user_roles_json)

    json_data_str = serialize('json', all_chatroles)
    json_data = json.loads(json_data_str)

    data = []
    for i in range(len(json_data)):
        json_data[i]['fields']['id'] = json_data[i]['pk']

        # 数据处理
        created_at_second = iso_to_times(json_data[i]['fields']['created_at'])
        updated_at_second = iso_to_times(json_data[i]['fields']['updated_at'])
        json_data[i]['fields']['created_at'] = created_at_second
        json_data[i]['fields']['updated_at'] = updated_at_second

        # 处理context字段
        if json_data[i]['fields']['context']:
            context_str_dumps = json_data[i]['fields']['context']
            context_list_loads = json.loads(context_str_dumps)
            json_data[i]['fields']['context'] = context_list_loads

        # 连表查询key name
        if json_data[i]['fields']['model_id'] is None:
            json_data[i]['fields']['model_id'] = 0
            json_data[i]['fields']['model_name'] = ""
        else:
            json_data[i]['fields']['model_name'] = all_chatroles[i].model_id.name

        data.append(json_data[i]['fields'])


    res_mes = {
        "code": 0,
        "data": data
    }
    res_mes_json = json.dumps(res_mes, ensure_ascii=False)
    return HttpResponse(res_mes_json)


def roles_update(request):
    '''
    用户自主加角色
    POST
    暂时不写。先占位
    '''
    pass

